﻿using AutoMapper;
using Oplug.EntityFramework;
using Oplug.EntityFramework.RossLive;
using Oplug.CoolTower.DTO;
using Oplug.Services;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using FastReport;
using FastReport.Editor;

namespace Oplug.CoolTower
{
    public partial class FormReport : MetroFramework.Forms.MetroForm
    {
        private DTO.SysConfig cfg;
        private delegate ResultDto<object> EpicorUserLogin(string cfg, string username, string password, string company);
        private Utilities Utility;
        private DataSQL Datasource { get; set; }
        public FormReport(string[] args)
        {
            InitializeComponent();
            if (args != null && args.Length > 1)
            {
            }
            Utility = new Utilities();
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {            
            Utilities utility = new Utilities();
            cfg = utility.GetSysCfg();
            if (cfg != null)
            {
                this.Text += " V" + Application.ProductVersion;
                Utilities.CompName = cfg.Company;

                if (utility.CheckUpdate(cfg.AutoUpdateURL))
                {
                    if (MessageBox.Show("系统有新版本！确定立即更新吗？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        string path = AppDomain.CurrentDomain.BaseDirectory + "AutoUpdate.exe"; 
                        if (File.Exists(path))
                        {
                            ProcessStartInfo processStartInfo = new ProcessStartInfo()
                            {
                                FileName = "AutoUpdate.exe",
                                Arguments = "Oplug.Live " + Application.ProductVersion
                            };
                            Process proc = Process.Start(processStartInfo);
                            if (proc != null)
                            {
                                proc.WaitForExit();
                            }
                        }

                    }
                    else
                    {
                        System.Environment.Exit(0);
                    }
                }
                LoadDataSQL();
            }
        }
        private void LoadDataSQL()
        {
            using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
            {
                var resp = ObjServ.repository.GetAllList();
                var lists = Mapper.Map<List<DataSQLSimple>>(resp);
                dgvM.DataSource = lists;
                dgvM.Columns[0].Visible = false;
                dgvM.Columns[1].Visible = false;
                dgvM.Columns[2].HeaderCell.Value = "模板名称"; 
                dgvM.Columns[2].ReadOnly = true;
                dgvM.Columns[3].Visible = false;
            }
        }
        private void buttonSetup_Click(object sender, EventArgs e)
        {
            FormConfig form = new FormConfig();
            form.Show();
            form.Owner = this;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FormCodePrint form = new FormCodePrint();
            form.ShowDialog();
        }

        private void buttonBAQ_Click(object sender, EventArgs e)
        {
            FormBAQ form = new FormBAQ();
            form.ShowDialog();
        }

        private void ButtonPrint_Click(object sender, EventArgs e)
        {
            FastReportView();
        }

        public void RDLCView()
        {
            if (Datasource == null)
            {
                Utilities.Message("请先选择打印模板！", InfoType.Warning);
                return;
            }
            using (OplugLiveService Serv = new OplugLiveService(cfg.DBConn))
            {
                DataTable dt = Utility.SqlQuery(Serv.dbContext.Database, Datasource.SQLText);
                if (dt != null)
                {
                    if (checkBoxAuto.Checked)
                    {
                        using (PrintDoc printDoc = new PrintDoc())
                        {
                            printDoc.Run(string.Format("{0}/RDLC/{1}.rdlc", Application.StartupPath, Datasource.ViewName), dt);
                        }
                    }
                    else
                    {
                        FormPrint form = new FormPrint(string.Format("Oplug.Report.RDLC.{0}.rdlc", Datasource.ViewName), dt, "", Datasource.ViewName);
                        form.Show();
                    }
                }
            }
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            LoadDataSQL();
        }

        private DataTable currDt;
        private async void dgvM_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (cfg == null)
            {
                Utilities.Message("请先设置数据源！");
                return;
            }
            var row = dgvM.CurrentRow.DataBoundItem as DataSQLSimple;
            using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
            {
                var obj = await ObjServ.repository.GetAsync(row.ID);
                Datasource = obj;
                labelTemp.Text = "当前模板：" + obj.DisplayName;
                using (OplugLiveService Serv = new OplugLiveService(cfg.DBConn))
                {
                    currDt = Utility.SqlQuery(Serv.dbContext.Database, Datasource.SQLText);
                    dgvS.DataSource = currDt;
                }
                    
            }
        }

        private void FastReportView()
        {
            if (Datasource == null)
            {
                Utilities.Message("请先设置数据源！");
                return;
            }
            try
            {
                FastReport.Report report = new FastReport.Report();
                string filename = Application.StartupPath + @"\Tmp\" + Datasource.ViewName + ".frx";
                report.Load(filename);
                using (OplugLiveService Serv = new OplugLiveService(cfg.DBConn))
                {
                    DataSet data = new DataSet();
                    currDt.TableName = "DataTable";
                    data.Tables.Add(currDt);
                    report.RegisterData(data);
                    var ds = report.GetDataSource("DataTable");
                    ds.Enabled = true;
                    report.Show();
                }
            }
            catch (Exception ex)
            {
                Utilities.Message(ex.Message, InfoType.Error);
            }
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            List<string> columns = new List<string>();
            if(currDt==null)
            {
                Utilities.Message("暂无数据", InfoType.Error);
                return;
            }
            foreach (DataColumn col in currDt.Columns)
            {
                columns.Add(col.ColumnName);
            }
            FormFilter form = new FormFilter(columns);
            form.FilterChanged += DoFilter;
            form.ShowDialog();
            form.Owner = this;
        }
        void DoFilter(object sender, FormFilter.FilterWhereEventArgs e)
        {
            using (OplugLiveService Serv = new OplugLiveService(cfg.DBConn))
            {
                currDt = Utility.SqlQuery(Serv.dbContext.Database, Datasource.SQLText + e.StrWhere);
                dgvS.DataSource = currDt;
            }
        }
    }
}
